import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { FormInstance } from 'antd/lib/form';
import { Modal, Button, Form, message, Input, Select } from 'antd';
import PropTypes from 'prop-types';

const FormItem = Form.Item;
const mapStateToProps = (state: any) => ({
  FleetMng: state.FleetMng,
});
class HandleModal extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.object,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      tenantOpt: [],
    };
  }

  componentDidUpdate(prevProps: any) {
    const { modalVisible, formData, dispatch } = this.props;
    if (modalVisible && modalVisible !== prevProps.modalVisible) {
      dispatch({
        type: 'FleetMng/getData',
        payload: {
          url: '/basedata/finddealerbylogin',
        },
        callback: (res: any) => {
          if (res.statusCode === '0') {
            const newOpt = res.data.map((t: any) => {
              return {
                label: t.name,
                value: t.sid,
              };
            });
            this.setState({ tenantOpt: newOpt });
          }
        },
      });
      this.formRef &&
        this.formRef.current?.setFieldsValue({
          ...formData,
        });
    }
  }

  handleSubmit = () => {
    this.formRef.current?.submit();
  };

  onFinish = (values: any) => {
    const { dispatch, formData, freshPage, tenantOpt } = this.props;
    let postData = {
      name: values.name,
      contactName: values.contactName,
      contactPhoneNumber: values.contactPhoneNumber,
      tenantName: formData.tenantSid ? formData.tenantName : values.tenantSid.label,
      tenantSid: formData.tenantSid ? formData.tenantSid : values.tenantSid.value,
    };
    let dType = 'FleetMng/postObjWithRes';
    let url = '/msalcohollock/fleet';
    if (formData?.sid) {
      dType = 'FleetMng/putObjWithRes';
      url = '/msalcohollock/fleet/' + formData?.sid;
    }
    this.setState({
      loading: true,
    });
    dispatch({
      type: dType,
      payload: {
        url: url,
        ...postData,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success(formData.sid ? '编辑成功' : '新增成功');
          this.close();
          freshPage();
        } 
      },
    }).finally(() =>
      this.setState({
        loading: false,
      }),
    );
  };

  close = () => {
    const { closeModal } = this.props;
    this.formRef.current && this.formRef.current.resetFields();
    closeModal();
  };

  render() {
    const { formData, modalVisible } = this.props;
    const { loading, tenantOpt } = this.state;
    const footer = (
      <div>
        <Button size="small" onClick={this.close}>
          取消
        </Button>
        <Button size="small" loading={loading} onClick={this.handleSubmit} type="primary">
          确定
        </Button>
      </div>
    );
    let title = formData.sid ? '编辑车队' : '新增车队';

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: {
          span: 6,
          // offset: 4,
        },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: {
          span: 14,
        },
        md: { span: 16 },
      },
    };

    return (
      <Modal title={title} footer={footer} visible={modalVisible} width={700} onCancel={this.close}>
        <Form style={{ marginTop: 12 }} ref={this.formRef} onFinish={this.onFinish}>
          <FormItem
            {...formItemLayout}
            label="车队名称"
            colon={false}
            name="name"
            // rules={[
            //   {
            //     required: true,
            //     message: '请输入车队名称,只能输入中英文、数字及特殊字符',
            //     whitespace: true,
            //     pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\s\w]+$/,
            //   },
            // ]}
            rules={[{ required: true, message: '不能输入空字符', pattern: /^\S+$/ }]}
          >
            <Input placeholder="请输入车队名称" maxLength={50} />
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="车队联系人"
            colon={false}
            name="contactName"
            // rules={[
            //   {
            //     required: true,
            //     message: '只能输入中英文、数字及特殊字符',
            //     pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\s\w]+$/,
            //   },
            // ]}
            rules={[{ required: true, message: '不能输入空字符', pattern: /^\S+$/ }]}

          >
            <Input placeholder="请输入车队联系人" maxLength={50} />
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="联系方式"
            colon={false}
            name="contactPhoneNumber"
            // rules={[
            //   {
            //     required: true,
            //     message: '只能输入中英文、数字及特殊字符',
            //     pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\s\w]+$/,
            //   },
            // ]}
            rules={[{ required: true, message: '不能输入空字符', pattern: /^\S+$/ }]}
          >
            <Input placeholder="请输入手机号或邮箱" maxLength={50} />
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="关联租户"
            colon={false}
            name="tenantSid"
            rules={[{ required: true, message: '请选择关联租户' }]}
          >
            <Select
              placeholder="请选择租户"
              options={tenantOpt}
              disabled={formData.tenantSid}
              showSearch
              optionFilterProp="label"
              labelInValue
            ></Select>
          </FormItem>
        </Form>
      </Modal>
    );
  }
}
export default connect(mapStateToProps)(HandleModal);
